package com.example.chess.api;

import com.example.chess.game.ChatManager;
import com.example.chess.game.OnlineUserManager;
import com.example.chess.game.Room;
import com.example.chess.game.RoomManager;
import com.example.chess.mapper.UserMapper;
import com.example.chess.model.User;
import com.example.chess.util.ChatRequest;
import com.example.chess.util.ChatResponse;
import com.example.chess.util.ResState;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;

@Component
public class ChatAPI extends TextWebSocketHandler {
    @Resource
    private RoomManager roomManager;

    @Resource
    private ChatManager chatManager;

    @Resource
    private UserMapper userMapper;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (session.getAttributes().get("user") == null){
            // 未登录
            System.out.println("未登录");
            return;
        }
        User user = (User)session.getAttributes().get("user");
        chatManager.enterChat(user.getUserId() ,session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.getAttributes().get("user") == null){
            // 未登录
            return;
        }
        User user = (User)session.getAttributes().get("user");
        chatManager.outChat(user.getUserId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if (session.getAttributes().get("user") == null){
            // 未登录
            return;
        }
        User user = (User)session.getAttributes().get("user");
        chatManager.outChat(user.getUserId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        ChatResponse response = new ChatResponse();
        if (session.getAttributes().get("user") == null){
            response.setState(ResState.FAIL);
            response.setReason("notlogin");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            System.out.println("玩家未登录");
            return;
        }
        User user = (User)session.getAttributes().get("user");// 得到当前发送消息的用户
        // 获取数据载荷
        String payload = message.getPayload();
        // 解析为对象
        ChatRequest request = objectMapper.readValue(payload, ChatRequest.class);
        String requestMessage = request.getMessage();// 得到消息

        // 得到对应的房间
        Room room = roomManager.getRoomByUser(user.getUserId());
        if (room == null){
            response.setState(ResState.FAIL);
            response.setReason("outline");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            return;
        }
        User thatUser = room.getUser1() == user ? room.getUser2() : room.getUser1();// 对方用户
        // 得到对方的 session
        WebSocketSession thatSession = chatManager.getSession(thatUser.getUserId());
        if (thatSession == null){
            response.setState(ResState.FAIL);
            response.setReason("outline");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            return;
        }
        // 向双方推送消息
        response.setState(ResState.SUCCESS);
        response.setMessage(requestMessage);
        response.setUserId(user.getUserId());
        response.setNickname(userMapper.getUserById(user.getUserId()).getNickname());

        // 向玩家一发送
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        // 向玩家二发送
        thatSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }
}
